import { program } from 'commander'
import fs from 'fs-extra'
import dotenv from 'dotenv'
import { Convertor } from './Convertor.js'
import env, { ICmdOption } from './Env.js'
import path from 'path'

const rmQuotes = (val: string): string => {
    const rst = val.match(/(['"])(.+)\1/)
    if (rst != null) return rst[2]
    return val
}

program.option('-p, --project <path>', '[MUST] the unity project root', rmQuotes)
    .option('-i, --input <path>', '[MUST] the input psd path', rmQuotes)
    .option('-n, --name <string>', '[MUST] the prefab name')
    .option('-d, --debug', 'use debug mode')
    .parse(process.argv)

const opts = program.opts()
console.log('options:', opts)
env.opts = opts as ICmdOption

if (!fs.existsSync(env.opts.project)) {
    console.error('[ERROR] project not exists:', env.opts.project)
    process.exit(1)
}

if (!fs.existsSync(env.opts.input)) {
    console.error('[ERROR] input psd not exists:', env.opts.input)
    process.exit(1)
}

// read .env file, it's optional
const cfg = dotenv.config({ path: path.join(env.opts.project, '.psd2prefab') })
if (cfg.error !== undefined) {
    console.log('.env read error, never mind')
} else {
    env.cfg.PNG_ROOT = process.env.PNG_ROOT ?? 'Assets/AssetSources/ui/atlas/$name$'
    env.cfg.PREFAB_ROOT = process.env.PREFAB_ROOT ?? 'Assets/AssetSources/ui/instruction'
    if (process.env.NOT_ART_FONTS !== undefined) {
        env.cfg.NOT_ART_FONTS = process.env.NOT_ART_FONTS.split(';')
    }
}

const cvt = new Convertor()
await cvt.make()
